package com.scs.application.modules.order.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.scs.application.core.exceptions.BusinessException;
import com.scs.application.core.model.CommonResult;
import com.scs.application.modules.base.entity.HospitalThirdPlatform;
import com.scs.application.modules.order.dto.OrderDTO;
import com.scs.application.modules.order.dto.PushThirdOrderStatusDTO;
import com.scs.application.modules.order.entity.PurchaseOrder;
import com.scs.application.modules.order.mapper.PurchaseOrderMapper;
import com.scs.application.modules.order.model.erp.ErpResponse;
import com.scs.application.modules.order.service.ThirdPlatformService;
import com.scs.application.modules.order.vo.ErpOrderVO;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * erp 采购对接（铁营）
 *
 */
@Service
@Slf4j
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ErpPlatformServiceImpl implements ThirdPlatformService {
    /**
     * 铁营接入第三方的供应商
     */
    private final List<String> keys = new ArrayList<String>() {{
        add("1286226304747229185");
        // TODO leisq 先特殊除了把，后面再想想怎么好好设计这里的对应关系
    }};

    public final String cacheKey = "data:order:ErpPlatform";
    // erp 提供给我们的客户编码
    public final String vencuscode = "1007614";

    // 推送订单地址
    public final String ORDER_URL = "/hr-ty-spd/spd/save/order";

    // 推送订单状态地址
    private final String ORDER_STATUS_URL = "/hr-ty-spd/spd/save/order/status";

    private RestTemplate restTemplate;

    private PurchaseOrderMapper purchaseOrderMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pushOrder(List<OrderDTO> orderDTOS, HospitalThirdPlatform hospitalThirdPlatform) {
        if (orderDTOS == null || orderDTOS.size() == 0 || hospitalThirdPlatform == null) {
            return;
        }
        // 过滤出需要推送的采购单: 对应的供应商
        List<OrderDTO> orders = orderDTOS.stream().filter(o -> keys.contains(o.getSupplierKey())).collect(Collectors.toList());
        if (orders == null || orders.isEmpty() || orders.size() == 0) {
            return;
        }
        List<ErpOrderVO> pushVO = new ArrayList<>();
        orders.forEach(orderDTO -> {

            List<OrderDTO.OrderItemDTO> items1 = orderDTO.getItems();
            final int size = items1.stream().map(OrderDTO.OrderItemDTO::getMaterialErpCode).distinct().collect(Collectors.toList()).size();
            if (items1.size() != size) {
                throw new BusinessException("采购订单 " + orderDTO.getPoCode() + " 中不能有重复的ERP耗材");
            }

            ErpOrderVO pushOrder = new ErpOrderVO();
            pushOrder.setSpdcode(orderDTO.getPoCode());
            pushOrder.setVencuscode(this.vencuscode);
            // 明细
            List<OrderDTO.OrderItemDTO> items = orderDTO.getItems();
            List<ErpOrderVO.OrderItem> pushItems = new ArrayList<>(items.size());
            orderDTO.getItems().forEach(o -> {
                ErpOrderVO.OrderItem item = pushOrder.new OrderItem();
                item.setWarecode(o.getMaterialErpCode());
                item.setWareprice(o.getPrice());
                item.setWareqty(o.getQty());
                pushItems.add(item);
            });
            pushOrder.setWareList(pushItems);

            pushVO.add(pushOrder);
        });

        log.debug(pushVO.toString());

        HttpHeaders headers = new HttpHeaders();
        headers.add("token", hospitalThirdPlatform.getAccessToken());
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity httpEntity = new HttpEntity(pushVO, headers);

        log.info("推送订单给ERP请求信息 : {}", httpEntity);
        String url = buildUrl(hospitalThirdPlatform.getHostAndPort(), ORDER_URL);
        ResponseEntity<ErpResponse> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, ErpResponse.class);
        log.info("推送订单给ERP响应信息 : {}", response);

        ErpResponse erpResponse = response.getBody();

        // 200 推送成功 405 重复推送
        if (erpResponse.getCode() == 200 || erpResponse.getCode() == 405) {
            log.info("推送订单成功！");
        } else {
            log.info("推送订单失败！");
            throw new BusinessException("推送订单失败！ " + erpResponse);
        }

    }

    @Override
    public void pushOrderStatus(PushThirdOrderStatusDTO dto, HospitalThirdPlatform hospitalThirdPlatform) {
         /* 推送数据格式
        [{
            "vencuscode": "ERP客户编码",
                "pocode": "TEST-001",
                "postatus": 6
        }
        ]
        */
        PurchaseOrder po = dto.getOrder();

        if (!keys.contains(po.getSupplierId())) {
            return;
        }

        // 关闭订单
        JSONArray pushArray = new JSONArray();
        JSONObject pushObj = new JSONObject();
        pushObj.put("vencuscode", this.vencuscode);
        pushObj.put("pocode", po.getCode());
        pushObj.put("postatus", dto.getPoStatus());
        pushArray.add(pushObj);

        HttpHeaders headers = new HttpHeaders();
        headers.add("token", hospitalThirdPlatform.getAccessToken());
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity httpEntity = new HttpEntity(pushArray, headers);

        log.info("推送订单状态给ERP请求信息 : {}", httpEntity);
        String url = buildUrl(hospitalThirdPlatform.getHostAndPort(), ORDER_STATUS_URL);
        ResponseEntity<ErpResponse> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, ErpResponse.class);
        log.info("推送订单状态给ERP响应信息 : {}", response);

        ErpResponse erpResponse = response.getBody();

        // 200 推送成功 405 重复推送
        if (erpResponse.getCode() == 200 || erpResponse.getCode() == 405) {
            log.info("推送订单状态成功！");
        } else {
            log.info("推送订单状态失败！{}", erpResponse);
        }

    }


    @Override
    public boolean getOrderStatus(List<OrderDTO> orderDTOS, HospitalThirdPlatform hospitalThirdPlatform) {
        return false;
    }

    @Override
    public void getDeliveries(List<OrderDTO> orderDTOS, HospitalThirdPlatform hospitalThirdPlatform) {

    }

    @Override
    public boolean notifyInOrder(List<OrderDTO> orderDTOS, HospitalThirdPlatform hospitalThirdPlatform) {
        return false;
    }

    @Override
    public CommonResult test(HospitalThirdPlatform hospitalThirdPlatform) {
        return null;
    }

}

